<template>
  <div>
    <el-table-form ref="dataForm" class="form" :model="query">
      <el-form-item label="商品分类:" prop="orgSNNo">
        <el-tree-select
          v-model="query.gtId"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'gtId',
              label: 'gtName',
              disabled: 'disabled',
            },
            data: goodsTreeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="商品名称:">
        <el-select v-model="query.goodsId" clearable>
          <el-option v-for="(l,i) in goodsTypesDetailList" :key="i" :value="l.goodsId" :label="l.goodsName" />
        </el-select>
      </el-form-item>
      <el-form-item label="波动方式:">
        <el-select v-model="query.priceType" clearable>
          <el-option v-for="(l,i) in priceTypeMap" :key="i" :value="l.value" :label="l.desc" />
        </el-select>
      </el-form-item>
      <el-form-item label="生效机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.scopeOrgSNNo"
          :clearable="true"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: orgTreeData
          }"
        />
      </el-form-item>
      <el-form-item label="状态:">
        <el-select
          v-model="query.statusArray"
          multiple
          placeholder="请选择"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="波动价格:">
        <el-input v-model="query.price" clearable placeholder="请输入" maxlength="6" @input="query.price=query.price.replace(/[^\d.]/g, '').replace(/^0\d+|^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(.*\..{2}).*$/,'$1')" @blur="formatInput($event)" />
      </el-form-item>

      <template v-slot:btns>
        <el-button v-permission="[10020303,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button v-permission="[10020303,2]" type="primary" icon="el-icon-s-check" @click="success1">一级审核</el-button>
        <el-button v-permission="[10020303,3]" type="primary" icon="el-icon-s-check" @click="success2">二级审核</el-button>
        <el-button v-permission="[10020303,4]" type="primary" icon="el-icon-s-check" @click="success3">审核（终极）</el-button>
        <el-button v-permission="[10020303,5]" type="primary" icon="el-icon-document-delete" @click="fail">驳回</el-button>
        <el-button v-permission="[10020303,6]" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @selection-change="handleSelectionChange"
      @fetch="fetchData"
      @row-click="clcikCurrentRow"
    />

  </div>
</template>

<script>
  import { goodsTypeDetail, CmsSpecialAuditData, CmsSpecialPriAudit, specialPriceAuditExport } from '@/api'
  import { parseTime, formatColumnMap } from '@/utils'
  export default {
    name: 'auditMode',
    props: ['orgTreeData', 'goodsTreeData', 'exportDomain'],
    data() {
      return {
        options: [{
          value: 0,
          label: '一级待审'
        }, {
          value: 1,
          label: '二级待审'
        }, {
          value: 2,
          label: '已生效'
        }, {
          value: 3,
          label: '已失效'
        }, {
          value: 4,
          label: '已驳回'
        }],
        multipleSelection: [],
        priceTypeMap: [{ 'value': 1, 'desc': '下浮', 'key': 'Fluctuating' }, { 'value': 2, 'desc': '固定', 'key': 'Fixed' }],
        goodsTypesDetailList: [],
        query: {
          goodsId: null,
          statusArray: [0, 1],
          scopeOrgSNNo: ''
        },
        searchParams: {},
        tableData: {
          total: 0,
          column: [
            { type: 'index' },
            { type: 'selection' },
            { label: '客户名称', prop: 'csmName', width: 120 },
            { label: '客户编号', prop: 'csmCode', width: 120 },
            { label: '生效机构', prop: 'scopeOrgName', width: 240 },
            { label: '商品名称', prop: 'goodsName', width: 120 },
            { label: '波动方式', prop: 'priceType', width: 80,
              render: (h, { row }) => <span>{row.priceType === 1 ? '下浮' : row.priceType === 2 ? '固定' : '未知' }</span>
            },
            { label: '价格', prop: 'price', width: 80, align: 'right',
              render: (h, { row, column }) => <span>{row.price && row.price.toFixed(2) }</span>
            },
            { label: '时效范围', prop: 'startDt', width: 300,
              render: (h, { row, column }) => <span>{this.timeformat(row, column) }</span>
            },
            {
              label: '远距配送费', prop: 'spFee', width: 80, align: 'right', formatter: row => this.formatFixed(row.spFee)
            },
            { label: '上楼费', prop: 'lpFee', width: 80, align: 'right', formatter: row => this.formatFixed(row.lpFee) },
            { label: '服务费', prop: 'tpFee', width: 80, align: 'right', formatter: row => this.formatFixed(row.tpFee) },
            { label: '状态', prop: 'checkStatus', width: 80,
              render: (h, { row, column }) => <span>{formatColumnMap(this.options, 'value', row.checkStatus, 'label') }</span>
            },
            { label: '申请人', prop: 'applyUser', width: 120 },
            { label: '申请时间', prop: 'applyDt', width: 140,
              render: (h, { row }) => <span>{row.applyDt && parseTime(row.applyDt, '{y}-{m}-{d} {h}:{i}')}</span>
            },
            { label: '关键字', prop: 'keyName', width: 80 }
          ],
          data: []
        }
      }
    },
    created() {
      this.query.gtId = this.goodsTreeData[0].gtId
      this.selectTreeChange({ gtId: this.goodsTreeData[0].gtId })
    },
    methods: {
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      formatFixed(val) {
        let result = 0
        if (val) {
          result = Number((val >> 1) | 0) / 100
        }
        return result
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        if (this.query.statusArray.length === 5) {
          this.query.statusArray = []
        }
        const query = {
          ...this.query,
          currentPage,
          pageSize,
          expired: this.query.statusArray.length === 0 ? '0' : '2'
        }
        delete query.date
        if (!query.goodsId) {
          delete query.goodsId
        }
        if (!query.scopeOrgSNNo) {
          delete query.scopeOrgSNNo
        }
        if (query.statusArray.indexOf(3) > -1) {
          if (query.statusArray.length === 1) {
            query.statusArray = []
            query.expired = 1
          }
          if (query.statusArray.length > 1) {
            query.expired = 3
          }
        }
        const res = await CmsSpecialAuditData(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        this.tableData.data.forEach((item) => {
          var endDt = new Date(item.endDt).getTime()
          var nowDt = new Date().getTime()
          console.log('1111')
          if (endDt < nowDt) {
            item.checkStatus = 3
            console.log('222')
          }
        })
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
        // console.log(val, 'val')
      },
      clcikCurrentRow(row) {
        this.$refs.lbTable.toggleRowSelection(row)
        // console.log(row)
      },
      // 选择商品分类
      async  selectTreeChange(value) {
        this.query.goodsId = null
        if (value) {
          await this.getGoodsTypeDetails(value.gtId)
        }
      },
      // 获取商品分类详情
      async getGoodsTypeDetails(val) {
        try {
          const res = await goodsTypeDetail({ gtId: val })
          this.goodsTypesDetailList = res.data.rows
          // console.log(res)
        } catch (error) {
          console.log(error)
        }
      },
      // 状态文本格式化
      statusMap(row, column) {
        if (row.endDt < row.nowDt) {
          return '已失效'
        }
        const val = row[column.property]
        if (val === 0) {
          return '一级待审'
        } else if (val === 1) {
          return '二级待审'
        } else if (val === 2) {
          return '已生效'
        } else if (val === 4) {
          return '已驳回'
        }
        return ''
      },
      // 时间格式化
      timeformat(row, column) {
        const startTime = parseTime(row.startDt, '{y}:{m}:{d} {h}:{i}:{s}')
        const endTime = parseTime(row.endDt, '{y}:{m}:{d} {h}:{i}:{s}')
        return `${startTime}至${endTime}`
      },
      // 导出
      async exportFile() {
        // console.log(this.exportDomain)
        // console.log(url)
        this.$confirm('确定要导出吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          var list = JSON.parse(JSON.stringify(this.tableData.column))
          list.shift()
          const value = {}
          list.forEach(l => {
            value[l.prop] = l.label
            return value
          })
          const params = {
            kv: value,
            paramInfo: { ...this.searchParams }
          }
          await specialPriceAuditExport(params).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        }).catch(() => {

        })
      },
      success1() {
        var val = this.multipleSelection.map(l => { return { categoryDetailId: l.categoryDetailId, checkStatus: l.checkStatus } })
        // console.log(val)
        if (!val || !val.length > 0) {
          this.$message.warning('请先选择要操作的数据')
          return
        }
        if (val.find(l => l.checkStatus !== 0)) {
          this.$message.warning('当前选择含有不是一级待审数据')
          return
        }
        this.$confirm(`确定同意一级审核当前数据？`, '提示', {
          type: 'info'
        }).then(() => {
          var params = {
            categoryDetailId: val.map(l => l.categoryDetailId).join(','),
            checkStatus: 1
          }
          try {
            CmsSpecialPriAudit(params).then(data => {
              this.$refs.lbTable.fetch({ currentPage: 1 })
            })
          } catch (e) {
            console.log(e)
          }
        })
      },
      success2() {
        var val = this.multipleSelection.map(l => { return { categoryDetailId: l.categoryDetailId, checkStatus: l.checkStatus } })
        // console.log(val)
        if (!val || !val.length > 0) {
          this.$message.warning('请先选择要操作的数据')
          return
        }
        if (val.find(l => l.checkStatus !== 1)) {
          this.$message.warning('当前选择含有不是二级待审数据')
          return
        }
        this.$confirm(`确定同意二级审核当前数据？`, '提示', {
          type: 'info'
        }).then(() => {
          var params = {
            categoryDetailId: val.map(l => l.categoryDetailId).join(','),
            checkStatus: 2
          }
          try {
            CmsSpecialPriAudit(params).then(data => {
              this.$refs.lbTable.fetch({ currentPage: 1 })
            })
          } catch (e) {
            console.log(e)
          }
        })
      },
      success3() {
        var val = this.multipleSelection.map(l => { return { categoryDetailId: l.categoryDetailId, checkStatus: l.checkStatus } })
        // console.log(val)
        if (!val || !val.length > 0) {
          this.$message.warning('请先选择要操作的数据')
          return
        }
        this.$confirm(`确定同意终极审核当前数据？`, '提示', {
          type: 'info'
        }).then(() => {
          var params = {
            categoryDetailId: val.map(l => l.categoryDetailId).join(','),
            checkStatus: 2
          }
          try {
            CmsSpecialPriAudit(params).then(data => {
              this.$refs.lbTable.fetch({ currentPage: 1 })
            })
          } catch (e) {
            console.log(e)
          }
        })
      },
      fail() {
        var val = this.multipleSelection.map(l => { return { categoryDetailId: l.categoryDetailId, checkStatus: l.checkStatus } })
        // console.log(val)
        if (!val || !val.length > 0) {
          this.$message.warning('请先选择要操作的数据')
          return
        }
        this.$confirm(`确定驳回吗？`, '提示', {
          type: 'info'
        }).then(() => {
          var params = {
            categoryDetailId: val.map(l => l.categoryDetailId).join(','),
            checkStatus: 4
          }
          try {
            CmsSpecialPriAudit(params).then(data => {
              if (data.success) {
                this.$message.success('驳回成功')
                this.$refs.lbTable.fetch({ currentPage: 1 })
              }
            })
          } catch (e) {
            console.log(e)
          }
        })
      },
      // 格式化金额
      formatInput(e) {
        if (e.target.value) {
          e.target.value = (e.target.value * 1).toFixed(2)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  /deep/.el-select__tags {
    overflow: hidden;
    span {
      display: flex;
    }
  }
}
</style>

